package com.shiyi.strategy.imp;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.shiyi.service.SystemConfigService;
import com.shiyi.strategy.FileUploadStrategy;
import com.shiyi.utils.DateUtil;
import lombok.RequiredArgsConstructor;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.qcloud.cos.region.Region;

import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;


@Service("qCloudUploadStrategyImpl")
@RequiredArgsConstructor
public class QCloudUploadStrategyImpl implements FileUploadStrategy  {

    private final Logger logger = LoggerFactory.getLogger(QCloudUploadStrategyImpl.class);

    private final SystemConfigService systemConfigService;

    private final FileStorageService service;


    //API密钥secretId
    private final String secretId = "AKIDqa7WiaKuIUSCh08LalK4ENKATjmeJky1";
    //API密钥secretKey
    private final String secretKey = "vb2FDe0CByZzFLyQgiPuELDtPksqbAVc";
    //存储桶所属地域
    private final String region = "ap-chengdu";
    //存储桶空间名称
    private final String bucketName = "blog-1314185317";
    //存储桶访问域名
    private final String path = "https://blog-1314185317.cos.ap-chengdu.myqcloud.com";

    private final String prefix = "/images/";

    private final String platform = "qcloud-1";

    private String baseUrl;

    public String upload(File file) {
        //生成唯一文件名
        String newFileName = generateUniqueName(file.getName());
        //文件在存储桶中的key
        String key = prefix + newFileName;
        //声明客户端
        COSClient cosClient = null;
        try {
            //初始化用户身份信息(secretId,secretKey)
            COSCredentials cosCredentials = new BasicCOSCredentials(secretId, secretKey);
            //设置bucket的区域
            ClientConfig clientConfig = new ClientConfig(new Region(region));
            //生成cos客户端
            cosClient = new COSClient(cosCredentials, clientConfig);
            //创建存储对象的请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
            //执行上传并返回结果信息
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            return path + key;
        } catch (CosClientException e) {
            e.printStackTrace();
        } finally {
            cosClient.shutdown();
        }
        return null;
    }

    @Override
    public String fileUpload(MultipartFile multipartFile,String suffix) {
        String newFileName = generateUniqueName(Objects.requireNonNull(multipartFile.getOriginalFilename()));
        String date = DateUtil.dateTimeToStr(DateUtil.getNowDate(), DateUtil.YYYYMMDD)  + "/";
        String key = prefix + date + newFileName;
        COSClient cosClient = null;
        File file;
        try {
            file = File.createTempFile("temp", null);
            multipartFile.transferTo(file);
            COSCredentials cosCredentials = new BasicCOSCredentials(secretId, secretKey);
            ClientConfig clientConfig = new ClientConfig(new Region(region));
            cosClient = new COSClient(cosCredentials, clientConfig);
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
            cosClient.putObject(putObjectRequest);
            return path + key;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            cosClient.shutdown();
        }
        return null;
    }

    public String generateUniqueName(String originalName) {
        return UUID.randomUUID() + originalName.substring(originalName.lastIndexOf("."));
    }


    /**
     * 批量删除文件
     * @return
     */
    @Override
    public Boolean deleteFile(String ...keys) {
        for (String key : keys) {
            String[] str = key.split(baseUrl);
            FileInfo fileInfo = new FileInfo()
                    .setPlatform(platform)
                    .setFilename(str[1]);
            service.delete(fileInfo);
        }
        return true;
    }

    public boolean deleteFile(String fileName) {
        String key = prefix + fileName;
        COSClient cosclient = null;
        try {
            //初始化用户身份信息(secretId,secretKey)
            COSCredentials cosCredentials = new BasicCOSCredentials(secretId, secretKey);
            //设置bucket的区域
            ClientConfig clientConfig = new ClientConfig(new Region(region));
            // 生成cos客户端
            cosclient = new COSClient(cosCredentials, clientConfig);
            // 指定要删除的 bucket 和路径
            cosclient.deleteObject(bucketName, key);
            // 关闭客户端(关闭后台线程)
            cosclient.shutdown();
        }catch (CosClientException e) {
            e.printStackTrace();
        }
        return true;
    }
}
